package fu.capstone.hanoicityguide.presentation.fragment.home;

import java.io.File;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
import fu.capstone.hanoicityguide.R;
import fu.capstone.hanoicityguide.business.bo.home.HomeBO;
import fu.capstone.hanoicityguide.business.bo.home.HomeBOImp;
import fu.capstone.hanoicityguide.business.model.Home;
import fu.capstone.hanoicityguide.common.billing.utils.Constants;
import fu.capstone.hanoicityguide.common.billing.utils.IabHelper;
import fu.capstone.hanoicityguide.common.billing.utils.IabResult;
import fu.capstone.hanoicityguide.common.billing.utils.Inventory;
import fu.capstone.hanoicityguide.common.billing.utils.Purchase;
import fu.capstone.hanoicityguide.common.utility.CheckForUpdatingUtil;
import fu.capstone.hanoicityguide.common.utility.DownloadMapFiles;
import fu.capstone.hanoicityguide.common.utility.InternetSetting;
import fu.capstone.hanoicityguide.common.utility.LocationSetting;
import fu.capstone.hanoicityguide.common.vgservice.VoiceGuidanceService;
import fu.capstone.hanoicityguide.dataaccess.base.BaseDAOImpl;
import fu.capstone.hanoicityguide.presentation.adapter.ViewPagerAdapter;

@SuppressLint("ValidFragment")
public class HomeFragment extends Fragment {

	private TextView txtOverview;
	private TextView txtHistory;
	private HomeBO homeBO;
	private ViewPager imgFragment;
	private ViewPagerAdapter vpagerAdapter;
	private Home home;
	private SearchView searchView;
	private DrawerLayout drawer;
	private String keyword;
	private BaseDAOImpl dao;
	private Menu menu = null;
	private SharedPreferences pref;
	private boolean activated;
	private IabHelper mHelper;
	public static boolean isPurchased;
	public ProgressDialog progressDialog;

	// private Button btnRestore;
	// private Button btnDelete;
	// private Button btnCreate;
	// private Button btnPurchase;

	public HomeFragment(DrawerLayout drawer) {
		this.drawer = drawer;
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		getActivity().getActionBar().setTitle("Home");
		super.onResume();

		try {
			setUpInAppBilling();
			File fileDir = new File(Environment.getExternalStorageDirectory()
					+ "/vietnam-latest.osm-gh");
			File[] listFile = fileDir.listFiles();

			if (listFile.length != 0) {
				for (int i = 0; i < listFile.length; i++) {
					if (listFile[i].getName().endsWith(".bin")) {
						Log.v("List File Name", listFile[i].getName());
						listFile[i]
								.renameTo(new File(Environment
										.getExternalStorageDirectory()
										+ "/vietnam-latest.osm-gh", listFile[i]
										.getName().substring(
												0,
												listFile[i].getName()
														.lastIndexOf("."))));
					}
				}
			}
		} catch (Exception e) {
			Log.v("HomeFragment : ", "Rename offline map file name");
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_home, container,
				false);

		pref = getActivity().getSharedPreferences("Service",
				Context.MODE_PRIVATE);
		activated = pref.getBoolean("Activated", false);

//		setUpInAppBilling();
		try {
			setHasOptionsMenu(true);
			txtHistory = (TextView) rootView.findViewById(R.id.txtHomeHistory);
			txtOverview = (TextView) rootView
					.findViewById(R.id.txtHomeOverview);
			imgFragment = (ViewPager) rootView.findViewById(R.id.homePager);

			homeBO = new HomeBOImp(getActivity());
			home = homeBO.browseHome();

			txtHistory.setText(home.getHistory());
			txtOverview.setText(home.getOverview());

			vpagerAdapter = new ViewPagerAdapter(getActivity(),
					home.getArrImage());
			imgFragment.setAdapter(vpagerAdapter);

			dao = new BaseDAOImpl(getActivity());

			File fileDir = new File(Environment.getExternalStorageDirectory()
					+ "/vietnam-latest.osm-gh");
			File[] listFile = fileDir.listFiles();

			if (listFile.length != 0) {
				for (int i = 0; i < listFile.length; i++) {
					if (listFile[i].getName().endsWith(".bin")) {
						Log.v("List File Name", listFile[i].getName());
						listFile[i]
								.renameTo(new File(Environment
										.getExternalStorageDirectory()
										+ "/vietnam-latest.osm-gh", listFile[i]
										.getName().substring(
												0,
												listFile[i].getName()
														.lastIndexOf("."))));
					}
				}
			}

		} catch (Exception e) {
			Log.e("Home Fragment", e.toString());
		}

		return rootView;
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		// create option menu in actionbar
		inflater = getActivity().getMenuInflater();
		inflater.inflate(R.menu.home_menu, menu);
		setMenu(menu);

		if (!pref.getBoolean("Activated", false)) {
			getMenu().getItem(1).setTitle(R.string.action_enable_vg);
		} else {
			getMenu().getItem(1).setTitle(R.string.action_disable_vg);
		}

		super.onCreateOptionsMenu(menu, inflater);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// create event for options item
		switch (item.getItemId()) {
		case R.id.action_search_home:
			// search all in home fragment
			Fragment listPlace = new ListPlaceFragment(drawer);
			FragmentManager fragmentManager = getFragmentManager();
			FragmentTransaction fTransaction = fragmentManager
					.beginTransaction();
			fTransaction.addToBackStack("ListPlace");
			fTransaction.replace(R.id.frame_container, listPlace).commit();
			getActivity().setTitle("Search Place");

			break;
		case R.id.action_vg_service:
			// enable(disable) voice guidance service
			/*
			 * This part is use to start the service, remember to call
			 * stopService
			 */
			pref = getActivity().getSharedPreferences("Service",
					Context.MODE_PRIVATE);
			activated = pref.getBoolean("Activated", false);
			LocationSetting locationSetting = new LocationSetting(getActivity());
			if (activated == false) {
				// User hasn't actived the service ->
				// activate it
				if (locationSetting.getGPSSetting(getActivity())) {
					Intent service_intent = new Intent(getActivity(),
							VoiceGuidanceService.class);
					getActivity().startService(service_intent);
					SharedPreferences.Editor editor = pref.edit();
					editor.putBoolean("Activated", true);
					editor.commit();
					getMenu().getItem(1).setTitle(R.string.action_disable_vg);
					Toast.makeText(getActivity(),
							"Voice Guidance Service Started!",
							Toast.LENGTH_LONG).show();
				} else {
					locationSetting.showSettingsAlert();
				}
			}
			if (activated == true) {
				Intent service_intent = new Intent(getActivity(),
						VoiceGuidanceService.class);
				getActivity().stopService(service_intent);
				SharedPreferences.Editor editor = pref.edit();
				editor.putBoolean("Activated", false);
				editor.commit();
				getMenu().getItem(1).setTitle(R.string.action_enable_vg);
				Toast.makeText(getActivity(),
						"Voice Guidance Service Disabled!", Toast.LENGTH_LONG)
						.show();
			}

			break;

		case R.id.action_purchase:
			// purchase for map offline
			try {
				InternetSetting internetSetting = new InternetSetting(
						getActivity());
				if (internetSetting.getConnectivityStatus(getActivity())) {
					purchase();
				} else {
					internetSetting.showSettingsAlert();
				}
			} catch (Exception e) {

			}
			break;

		case R.id.action_checkforupdating:
			// check for updating
			InternetSetting internetSetting = new InternetSetting();
			if (internetSetting.getConnectivityStatus(getActivity())) {
				new CheckForUpdatingUtil(getActivity()).execute();
			} else {
				internetSetting.showSettingsAlert();
			}
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	public void setMenu(Menu menu) {
		this.menu = menu;
	}

	public Menu getMenu() {
		return this.menu;
	}

	private void setUpInAppBilling() {
		// set up interface
		mHelper = new IabHelper(this.getActivity(),
				Constants.base64EncodedPublicKey);

		// services binding
		mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
			public void onIabSetupFinished(IabResult result) {
				if (!result.isSuccess()) {
					// Oh noes, there was a problem.
					Toast.makeText(getActivity(),
							"Problem setting up In-app Billing: " + result,
							Toast.LENGTH_SHORT).show();
				} else {
					// if success, check item is purchase or not
					Log.v("Setup InApp Billing", "Setup finished");
					checkPurchased();
				}
			}
		});

	}

	// This function run on background,so it don't return result immediatelly
	private void checkPurchased() {
		IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
			public void onQueryInventoryFinished(IabResult result,
					Inventory inventory) {

				if (result.isFailure()) {
					// handle error here

				} else {
					isPurchased = inventory.hasPurchase(Constants.PRODUCT_ID);
					Log.v("isPurchased", String.valueOf(isPurchased));
				}
			}
		};
		mHelper.queryInventoryAsync(mGotInventoryListener);
	}

	private void purchase() {

		if (isPurchased) {
			Toast.makeText(getActivity(), "You purchased this item before",
					Toast.LENGTH_SHORT).show();
		} else {
			mHelper.launchPurchaseFlow(getActivity(), Constants.PRODUCT_ID,
					Constants.ORDER_ID, mPurchaseFinishedListener, "");
		}

		// // if (isPurchased) {
		// // Toast.makeText(getActivity(), "You purchased this item before",
		// // Toast.LENGTH_SHORT).show();
		// // } else {
		// mHelper.launchPurchaseFlow(getActivity(), Constants.PRODUCT_ID,
		// Constants.ORDER_ID, mPurchaseFinishedListener, "");
		// // }

	}

	IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
		public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
			if (result.isFailure()) {
				Toast.makeText(getActivity(), "Error purchased " + result,
						Toast.LENGTH_SHORT).show();
				return;
			} else if (purchase.getSku().equals(Constants.PRODUCT_ID)) {
				Toast.makeText(getActivity(),
						"Purchased successful! Start downloading.",
						Toast.LENGTH_SHORT).show();
				File fileDir = new File(Environment.getExternalStorageDirectory()
						+ "/vietnam-latest.osm-gh");
				if (!fileDir.isDirectory()){
					String[] url = {
							"https://dl.dropboxusercontent.com/s/k132liwxb7o4a7v/edges?dl=0",
							"https://dl.dropboxusercontent.com/s/ag8yq1hms7i8jtv/geometry?dl=0",
							"https://dl.dropboxusercontent.com/s/uvuz30vbzlnr691/locationIndex?dl=0",
							"https://dl.dropboxusercontent.com/s/ffh0jy4mr9cdx1i/names?dl=0",
							"https://dl.dropboxusercontent.com/s/zf8d312gm74rj91/properties?dl=0",
							"https://dl.dropboxusercontent.com/s/4iuhyx1uvt3cnr4/nodes?dl=0",
							"https://dl.dropboxusercontent.com/s/y6cuobxyz1ltztv/vietnam.map?dl=0" };
					DownloadMapFiles dmf = new DownloadMapFiles(getActivity());
					dmf.execute(url);
				}
			}
		}
	};

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (mHelper == null) {
			return;
		}
		if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {
			super.onActivityResult(requestCode, resultCode, data);
		} else {
			Log.v("HomeFragment", "On Activity Result : Not in purchase");
		}
	}

}
